package service.purchasing.impl;

import dao.purchasing.OrderDao;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import model.purchasing.OrderDetail;
import model.purchasing.OrderMst;
import model.purchasing.OrderPrint;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import service.purchasing.OrderService;
import utility.NameValueList;
import utility.StringUtils;

@Service("orderService")
@Transactional(readOnly=true)
public class OrderServiceImpl implements OrderService {

    private static final Logger log = Logger.getLogger(OrderServiceImpl.class);
    
    //void LazyInitializationException 
    String mainQuery = "select distinct mst from OrderMst mst left join fetch mst.supplier supplier "+
            "left join fetch mst.orderDetails details left join fetch details.item item "+
            "left join fetch details.hadiah hadiah left join fetch details.unit unit ";
        
    @Autowired private OrderDao orderDao;
    
    @Transactional(readOnly=false)
    @Override
    public boolean save(OrderMst data) {
        return orderDao.saveData(data);
    }

    @Transactional(readOnly=false)
    @Override
    public boolean delete(OrderMst data) {
        return orderDao.delete(data);
    }

    @Override
    public OrderMst get(long id) {
        String q = mainQuery + " where mst.id = "+id;
        return orderDao.getByCustomQuery(q);
    }

    @Override
    public OrderMst get(String transNum) {
        String q = mainQuery + " where mst.id = "+StringUtils.fmtSQLString(transNum);
        return orderDao.getByCustomQuery(q);
    }

    @Override
    public String getTransNum(long id) {
        return (String) orderDao.getFieldValue("transNum", id);
    }

    @Override
    public List<OrderMst> getAll(int start, int num, Map<NameValueList, Object> params) {
        String query = mainQuery+StringUtils.getFilter(params);
        return orderDao.getAll(start, num, query);
    }

    @Override
    public List<NameValueList> getListByEntryId(long entryId) {
        String completeQuery = "select cast(ord.id as string) as key, ord.transNum as value from OrderMst as ord where autoId = "+entryId;
        return orderDao.getNameValueList(completeQuery);
    }

    @Override
    public JasperPrint printData(long autoId, long id) {
        String query;
        if (autoId>0) {query = mainQuery+ " where mst.autoId = "+autoId; }
        else {query = mainQuery+ " where mst.id = "+id; }
        
        try {
            List<OrderMst> orders = orderDao.getAll(query);
            List<OrderPrint> prints = new ArrayList<>();
            
            for (OrderMst mst:orders ) {
             
                for (OrderDetail detail:mst.getOrderDetails() ) {
                    OrderPrint orderPrint = new OrderPrint();
                    orderPrint.setDivisi(mst.getDivisi());
                    orderPrint.setId(mst.getId());
                    orderPrint.setTransDate(mst.getTransDate());
                    orderPrint.setTransNum(mst.getTransNum());
                    orderPrint.setAlamatSupplier(mst.getSupplier().getAlamat());
                    orderPrint.setKodeSupplier(mst.getSupplier().getKode());
                    orderPrint.setNamaSupplier(mst.getSupplier().getNama());
                    orderPrint.setPhoneSupplier(mst.getSupplier().getPhone());
                    orderPrint.setKontakSupplier(mst.getSupplier().getKontak());
                    orderPrint.setLeadTime(mst.getLeadTime());
                    orderPrint.setTop(mst.getAddTop() + mst.getTop());
                    orderPrint.setNotes(mst.getNotes());
                    orderPrint.setPkp(mst.getPkp()==true ? "PKP":"NON PKP");
                    orderPrint.setPpnTotal(mst.getPpn());
                    orderPrint.setSubtotal(mst.getSubtotal());
                    orderPrint.setDiskonTotal(mst.getDiskon());
                    orderPrint.setTotal(mst.getTotal());
                    
                    orderPrint.setAmount(detail.getAmount());
                    orderPrint.setBonusDesc(detail.getBonusDesc());
                    orderPrint.setDiskon(detail.getDiskon());
                    orderPrint.setPpn(detail.getPpn());
                    orderPrint.setDiskonDesc(detail.getDiskonDesc());
                    orderPrint.setFraksi(detail.getFraksi());
                    if (detail.getHadiah()!=null) {
                        orderPrint.setNamaHadiah(detail.getHadiah().getNama());
                        orderPrint.setPluHadiah(detail.getHadiah().getPlu());
                    }
                    
                    orderPrint.setPrice(detail.getPrice());
                    orderPrint.setQtyBonus(detail.getQtyBonus());
                    orderPrint.setQtyCrt(detail.getQtyCrt());
                    orderPrint.setQtyPcs(detail.getQtyPcs());
                    orderPrint.setSatuan(detail.getUnit().getKode());
                    orderPrint.setPlu(detail.getItem().getPlu());
                    orderPrint.setNamaItem(detail.getItem().getNama());
                    prints.add(orderPrint);
                }
            }
            
            String jasperReport = "./reports/trans/PurchaseOrder.jasper";
            return JasperFillManager.fillReport(jasperReport, null, new JRBeanCollectionDataSource(prints, false));
            
        }catch(JRException ex){
            log.error("error generate print", ex);
        }

        return null;
        
        /*
         select mst.id, mst.transNum, mst.transDate, mst.supplier.kode as kodeSupplier, mst.supplier.nama as namaSupplier, mst.supplier.alamat as alamatSupplier,
mst.supplier.phone as phoneSupplier, mst.supplier.kontak as kontakSupplier,
(case when mst.pkp=true then 'PKP' else 'NON PKP' end) as pkp,
mst.leadTime, (mst.top+mst.addTop) as top, mst.divisi,
mst.subtotal, mst.diskon as diskonTotal, 
mst.ppn as ppnTotal, mst.total, mst.notes,
mst.orderDetails.item.plu as plu, mst.orderDetails.item.nama as namaItem,
mst.orderDetails.hadiah.plu as pluHadiah, mst.orderDetails.hadiah.nama as namaHadiah,
mst.orderDetails.qtyCrt, mst.orderDetails.qtyPcs, mst.orderDetails.qtyBonus, mst.orderDetails.price, mst.orderDetails.diskon,
mst.orderDetails.ppn, mst.orderDetails.amount, mst.orderDetails.unit.kode as satuan, mst.orderDetails.fraksi, mst.orderDetails.diskonDesc, mst.orderDetails.bonusDesc
from OrderMst mst
*/
    }
    
}
